//
//  WHAuthorDetailViewController.m
//  GroupFourFM
//
//  Created by dllo on 15/12/26.
//  Copyright © 2015年 GroupFour. All rights reserved.
//

#import "WHAuthorDetailViewController.h"
#import "WSTrackModel.h"
#import "WSAlbumDetailTableViewCell.h"
#import "WSPlayViewController.h"
#import "WSAuthorHeader.h"
#import "WSAuthorheadView.h"
#import <WSProgressHUD.h>
#import "WSBmob.h"
#import <BmobSDK/Bmob.h>
#import "WSLoginViewController.h"

@interface WHAuthorDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate, WSAuthorheadViewDelegate>{
    
    WSProgressHUD *hud;
}

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *albumArray;
@property (nonatomic, strong) NSMutableArray *trackArray;
@property (nonatomic, strong) WSAuthorheadView *tableHeadView;
@property (nonatomic, assign) CGFloat cellHeight;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) UIImageView *overImage;
@property (nonatomic, copy) NSString *totalCount;
@property (nonatomic, strong) WSAuthorHeader *model;

@end

@implementation WHAuthorDetailViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
#pragma mark - 导航栏透明
    self.automaticallyAdjustsScrollViewInsets = NO;

    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"album_album_mask"] forBarMetrics:UIBarMetricsCompactPrompt];
    
    self.trackArray = [NSMutableArray array];
    [self getAuthorData];
    [self getData];
    [self createSubviews];
    //返回按钮
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.backgroundColor = CLEAR;
    [backButton setImage:[[UIImage imageNamed:@"btn_back_n"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    backButton.frame = CGRectMake(0, 0, 20, 30);
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    backButton.tintColor = [UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    hud = [[WSProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    
    [hud showWithString:nil maskType:WSProgressHUDMaskTypeBlack];
}
#pragma mark - 返回按钮方法
-(void)backButtonAction:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - 创建子视图
-(void)createSubviews {
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    self.myTableView.backgroundColor = CLEAR;
    [self.view addSubview:self.myTableView];
    
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.equalTo(@0);
    }];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    self.myTableView.rowHeight = 120.f;
    [self.myTableView registerClass:[WSAlbumDetailTableViewCell class] forCellReuseIdentifier:@"authorTrackCell"];
    
    self.currentPage = 1;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    self.myTableView.mj_footer = footer;
   
    [self creatHeadView];
}

#pragma mark - 创建头视图
-(void)creatHeadView
{
    self.tableHeadView = [[WSAuthorheadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT * 0.4)];
    self.tableHeadView.backgroundColor = CLEAR;
    self.tableHeadView.delegate = self;
    self.myTableView.tableHeaderView = self.tableHeadView;
}

#pragma mark - 请求主播数据
-(void)getAuthorData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/homePage?position=2&toUid=%ld&device=iphone&title=%@", self.uid, self.myTitle];
    
    [WSAppTools getDataWithURL:urlStr block:^(id result) {
        
        [[WSBmob shareBmob] selectRelationWithUid:[[NSUserDefaults standardUserDefaults] objectForKey:@"uId"] tableName:@"Collect_author" block:^(id results) {
            
            NSMutableArray *selectArr = results;
            _model = [WSAuthorHeader modelWithDictionary:result];
            for (BmobObject *object in selectArr) {
                NSString *name = [object objectForKey:@"authorName"];
                if ([name isEqualToString:_model.nickname]) {
                    _model.objectId = object.objectId;
                }
            }
            self.tableHeadView.model = _model;
            [self.myTableView reloadData];
        }];
        
    } error:^(NSError *error) {
        
    }];
}
#pragma mark - 请求数据
-(void)getData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/track/%ld/%ld/30?device=iPhone",self.uid,self.currentPage];
    [WSAppTools getDataWithURL:urlStr block:^(id result) {
        NSLog(@"%@",result);
        self.totalCount = [result objectForKey:@"totalCount"];
        NSMutableArray *array = [result objectForKey:@"list"];
        for (NSMutableDictionary *dic in array) {
            
            WSTrackModel *model = [WSTrackModel modelWithDictionary:dic];
            [self.trackArray addObject:model];
        }
        
        self.currentPage++;
        [self.myTableView.mj_footer endRefreshing];
        [self.myTableView reloadData];
        
        [hud dismiss];
    } error:^(NSError *error) {
        
        NSLog(@"数据请求失败 error");
    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 30;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.trackArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WSAlbumDetailTableViewCell *trackCell = [tableView dequeueReusableCellWithIdentifier:@"authorTrackCell"];
    
    WSTrackModel *model = [self.trackArray objectAtIndex:indexPath.row];
    
    trackCell.trackModel = model;
    
    return trackCell;
    
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.totalCount == NULL) {
        
        return @"发布的声音(0)";
    }
    NSString *secStr = [NSString stringWithFormat:@"发布的声音(%@)",self.totalCount];
    
    return secStr;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    WSPlayViewController *player = [WSPlayViewController sharaMusicPlayer];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:player];
    WSTrackModel *sing = [self.trackArray objectAtIndex:indexPath.row];
    player.song_id = sing.trackId;
    player.allMusicArray = self.trackArray;
    player.indexRow = indexPath.row;
    [self presentViewController:naVC animated:YES completion:^{
        
    }];
    
}
#pragma mark - scrollView协议方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y = scrollView.contentOffset.y;
    //NSLog(@"%f",y);
//    if (y < 0){
//        [self.backgroundImageView mas_updateConstraints:^(MASConstraintMaker *make) {
//        
//            make.top.mas_equalTo(y);
//            make.left.right.equalTo(self.tableHeadView);
//            make.bottom.equalTo(@25);
//        }];
//    }
}

#pragma mark - 关注协议方法
- (void)attentionAction {

    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
        if (_model.objectId != nil) {
            
            [self alertViewControllerWithTitle:@"取消关注？" content:nil block:^{
                
                [hud showWithString:nil];
                [[WSBmob shareBmob] deleteRelationWithObjectId:_model.objectId tableName:@"Collect_author" block:^(id results) {
                    
                    if ([results isEqualToString:@"successful"]) {
                        
                        _model.objectId = nil;
                    }
                    self.tableHeadView.model = _model;
                    [hud dismiss];
                }];
            }];
        }
        else {
            
            [hud showWithString:nil];
            [[WSBmob shareBmob] collectAuthorWithAuthorId:_model.uid title:_model.nickname content:_model.personDescribe image:_model.backgroundLogo block:^(id result) {
                
                if ([result isEqualToString:@"fail"] || result == nil) {
                    
                    [self alertViewControllerWithTitle:@"提示" content:@"关注失败"];
                }
                else {
                    
                    _model.objectId = result;
                }
                self.tableHeadView.model = _model;
                [hud dismiss];
            }];
        }
    }
    else {
        
        WSLoginViewController *loginVC = [[WSLoginViewController alloc] init];
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        navC.navigationBarHidden = YES;
        [self presentViewController:navC animated:YES completion:nil];
    }
}

- (void)alertViewControllerWithTitle:(NSString *)title content:(NSString *)content {
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertC addAction:action];
    [self presentViewController:alertC animated:YES completion:nil];
}

- (void)alertViewControllerWithTitle:(NSString *)title content:(NSString *)content block:(void(^)())block {
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        block();
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertC addAction:cancel];
    [alertC addAction:action];
    [self presentViewController:alertC animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
